package com.csw.shuanfa.CodeImprove.redlockThread.redLockHand;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    public RedisDistributedLock(StringRedisTemplate stringRedisTemplate) {
//        RedisDistributedLock.stringRedisTemplate = stringRedisTemplate;
//    }

    static int expireTime = 10;


    /**
     * @param lockKey
     * @param lockValue
     * @param waitTime  等待时间-单位秒
     * @return
     */
    public boolean tryAcquireLock(String lockKey, String lockValue, int waitTime) {
        long startTime = System.currentTimeMillis();
        while ((System.currentTimeMillis() - startTime) < waitTime * 1000) {
            Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, Duration.ofSeconds(expireTime));
            if (b) {
                return true; // 成功获取锁
            }
            try {
                Thread.sleep(100); // 等待一段时间后重试
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return false; // 获取锁超时
    }

    public void releaseLock(String lockKey, String lockValue) {
        String currentValue = stringRedisTemplate.opsForValue().get(lockKey);
        if (currentValue != null && currentValue.equals(lockValue)) {
            stringRedisTemplate.delete(lockKey);
        }
    }

    public Timer getTimer(String lockKey) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                stringRedisTemplate.expire(lockKey, expireTime, TimeUnit.SECONDS); // 续约锁的过期时间
                //System.out.println("续约锁" + new Date().toString() + lockKey);
            }
        }, 0, expireTime * 1000 / 2); // 每隔一半的过期时间续约一次
        return timer;
    }
}
